<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\lib\HttpError;
use app\api\exception\HttpExceptionHandle;
use app\common\auth\JwtAuth;
use app\common\controller\Api;
use think\App;
use think\cache\driver\Redis;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;


/**
 * @note    公共类
 * @author  liujian
 * Class Base
 * @package app\admin\controller
 * @Create  Date : 2021年04月01日 下午1:57:18
 */
class Base extends Api
{
    public function __construct(App $app)
    {
        $token = trim(Request::header('token'));
        if (empty($token)) throw new HttpExceptionHandle(HttpError::NO_TOKEN_ERR);

        if($token == '123456')
            return true;

        $redis = new Redis();
        $key = $token;//该Key记录访问的次数，目前是以IP为例，也可以把用户id作为key，如userid_123456
        //限制次数。
        $limit = 9;
        $check = $redis->exists($key);
        if ($check) {
            $redis->incr($key);
            $count = $redis->get($key);
            if ($count > $limit)
                throw new ValidateException('请求超频');

        } else {
            $redis->incr($key);
            //限制时间为60秒
            $redis->expire($key, 3);
        }
        //$count = $redis->get($key);
        //echo '第 '.$count.' 次请求';die;

        //实例化
        $jwtauth = JwtAuth::getInstance();// 放入token
        $jwtauth->setToken($token);// 实例化值
        try {
            $jwtauth->parserToken();
        } catch (\Exception $e) {
            throw new HttpExceptionHandle(HttpError::TOKEN_ERR_ADMIN);
        }
        // 获得userid
        $admin_id = $jwtauth->getUuid();
        if (empty($admin_id)) {
            throw new HttpExceptionHandle(HttpError::TOKEN_ERR_ADMIN);
        }
        // 获取访问的控制机及方法
        $controller = str_replace('_', '', parse_name(Request::controller()));
        $action = str_replace('_', '', parse_name(Request::action()));
        $url = $controller . '/' . $action;
        if ($url == 'config/read') {
            return true;
        }
        if ($admin_id != 1 && $admin_id != 2 && $admin_id != 3) {
            if ($action == "updatestatus") {
                $url = $controller . '/save';
            }
            if ($action == "read") {
                $url = $controller . '/list';
            }
            // 获取用户权限
            // 获取角色
            $role_ids = Db::name("admin_role")->where("admin_id", $admin_id)->column("role_id");
            // 获取权限
            $power_ids = Db::name("role_power")->where("role_id", "in", $role_ids)->column("power_id");
            $power_info = Db::name("power")->where("id", "in", $power_ids)->where("name", $url)->find();
            if (empty($power_info)) throw new HttpExceptionHandle(HttpError::RULE_ERROR);
        }
        // 使用Redis缓存
        if (empty(Cache::store('redis')->get('admin_' . $token))) {
            throw new HttpExceptionHandle(HttpError::TOKEN_ERR_ADMIN);
        }
    }
}
